import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';

import '../AppConfig/Config.dart';
import '../AppConfig/LocalStorage.dart';
import '../TabBar/TabbarView.dart';
import '../http/api.dart';
import '../l10n/messages.dart';
import 'package:image/image.dart' as img;
class ShipperAuth extends StatefulWidget {
  const ShipperAuth({super.key, required this.token});
  final String token;
  @override
  State<ShipperAuth> createState() => _ShipperAuthState();
}

class _ShipperAuthState extends State<ShipperAuth> {
  List titleList=["企业名称","统一社会信用代码\n（三证合一）","法定代表人姓名","注册地址"];
  List dataList =["","","",""];
  String? ConName;
  String? CardNum;
  String? Representative;
  String? Address;
  late String ChooseIndex="";
  final ImagePicker picker = new ImagePicker();
//用户本地图片
  File? _userImage;
  File? _userImage2;//存放获取到的本地路径
  int oneCheck =0;
  String cardImgStr="";
  TextEditingController _nametextEditingController = TextEditingController();
  Map dataMap={};
  String getFrontPath="";
  @override



  Future<DateTime?> _showDatePickerForTheme(BuildContext context) {
    return showDatePicker(
      context: context, // 上下文
      initialDate: DateTime.now(), // 初始化选中日期
      firstDate: DateTime.now(), // 开始日期
      lastDate: DateTime(2100, 1), // 结束日期
      currentDate: DateTime.now(), // 当前日期
      initialEntryMode: DatePickerEntryMode
          .calendarOnly, // 日历弹框样式 calendar: 默认显示日历，可切换成输入模式，input:默认显示输入模式，可切换到日历，calendarOnly:只显示日历，inputOnly:只显示输入模式
      selectableDayPredicate: (dayTime) {
        // 自定义哪些日期可选
        if (dayTime == DateTime(2022, 1, 1) || dayTime == DateTime(2100, 1, 1)) {
          return false;
        }
        return true;
      },
      builder: (context, child) {
        return Theme(
          data: ThemeData(
            primarySwatch: Colors.amber,
          ),
          child: child!,
        );
      },
      helpText: "请选择日期", // 左上角提示文字
      cancelText: "取消", // 取消按钮 文案
      confirmText: "确定", // 确认按钮 文案
      initialDatePickerMode: DatePickerMode.day, // 日期选择模式 默认为天
      useRootNavigator: true, // 是否使用根导航器
      textDirection: TextDirection.ltr, // 水平方向 显示方向 默认 ltr
    );
  }


  void uploadOcrAction() async {

    String? token = await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler)  {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio
        .post(
      MyServiceUrl.header+'api/system/dev/ocr/doOcr',
      data: {

        "type": "BL",
        "frontFileFormat": "jpg",
        "frontData": cardImgStr,
        "backFileFormat":"",
        "backData": "",
      },
      options: Options(
        sendTimeout: Duration(seconds: 2),
        receiveTimeout: Duration(seconds: 50),
      ),

    )
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(
            r.toString());
        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          print("code：$code");
          BrnToast.show(
            "识别成功",
            context,
            duration: BrnDuration.short,
          );
          dataMap=jsonMap['data']['result'];
          dataList=[dataMap['name'],dataMap['registrationNumber'],dataMap['legalRepresentative'],dataMap['address']];
          getFrontPath =jsonMap['data']['frontPath'];
        }
      });
    }).catchError((error) {
      print(error);
      ;
    });
  }


  String imageToBase64(File imageFile) {
    List<int> imageBytes = imageFile.readAsBytesSync();
    String base64String = base64Encode(Uint8List.fromList(imageBytes));

    return base64String;
  }


  void printImageMemorySize(File imageFile) {
    List<int> imageBytes = imageFile.readAsBytesSync();
    print('Original Image Memory Size: ${imageBytes.length} bytes');
  }

  Future<void> compressImage(File imageFile) async {
    List<int> imageBytes = await imageFile.readAsBytes();
    img.Image image = img.decodeImage(Uint8List.fromList(imageBytes))!;

    // Adjust the quality and size as needed
    img.Image compressedImage = img.copyResize(image, width: 1024);

    List<int> compressedBytes = img.encodeJpg(compressedImage, quality: 80);

    // Create a new File for the compressed image
    File compressedFile = File('${imageFile.path}_compressed.jpg');
    await compressedFile.writeAsBytes(compressedBytes);

    print('Compressed Image Size: ${compressedBytes.length} bytes');

    convertToBase64(compressedFile);
  }

  Future<void> convertToBase64(File imageFile) async {
    List<int> imageBytes = await imageFile.readAsBytes();
    String base64String = base64Encode(imageBytes);
    print('Base64 String: $base64String');
    cardImgStr =base64String;
    uploadOcrAction();

  }

  @override
  Widget build(BuildContext context) {
    var messages = AppLocalizations.of(context)!;
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor:Color.fromRGBO(248, 248, 248, 1),
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: Text("货主认证",style: TextStyle(fontWeight: FontWeight.w300,fontSize: 16.sp),),
        centerTitle: true,
        backgroundColor: Colors.white,
        actions: [
          TextButton(onPressed: (){
            Navigator.pushAndRemoveUntil(
              context,
              MaterialPageRoute(builder: (context) => TabbarView(pateIndex: 3,)), // 推入第二个页面
                  (route) => false, // 从栈中移除所有页面，包括当前页面和第一个页面
            );
          }, child: Text("暂不认证",style: TextStyle(color: Colors.black),))
        ],
      ),
      body:Column(
        children: [
          Expanded(child:
          ListView(

            children: [

              SizedBox(height: 2,),
              SizedBox(height: 20,child: Container(color: Colors.white,),),
              Container(
                color: Colors.white,
                height:40.h,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text("个人信息",style: TextStyle(fontSize: 12.sp,color: Color.fromRGBO(231, 112, 27, 0.85)),),
                        Image.asset("lib/Images/Authentication/圆形.png",height: 11.h,width: 11.w,),
                      ],
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text("123123",style: TextStyle(fontSize: 12.sp,color: Colors.white,)),
                        Text("------------",style: TextStyle(fontSize: 12.sp,color: Colors.black),),
                      ],
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text("企业信息",style: TextStyle(fontSize: 12.sp,color: Color.fromRGBO(231, 112, 27, 0.85)),),
                        Text("②",style: TextStyle(fontSize: 12.sp,color: Color.fromRGBO(231, 112, 27, 0.85)),),
                      ],
                    ),

                  ],

                ),
              ),
              SizedBox(height: 8.h,),
              Container(
                color: Colors.white,
                height: 140.h,
                child:Column(
                  // crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(height: 8.h,),
                    Row(
                      children: [
                        SizedBox(width: 18.w,),
                        Text("上传营业执照(必填)",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600),),
                      ],
                    ),

                    SizedBox(height: 8.h,),
                    Row(
                      // mainAxisAlignment: MainAxisAlignment.center,

                      children: [
                        SizedBox(width: 18.w,),
                        GestureDetector(
                          child:
                          _userImage!=null?
                          Stack(

                            children: [

                              Container(
                                height: 90.h,
                                width: 150.w,

                                child: Image.file(_userImage!) ,
                              ),
                              Center(
                                child: Image.asset("lib/Images/Authentication/重新上传.png" ,height: 20.h,width: 50.w,),
                              ),
                            ],
                            alignment: Alignment.center,
                          )

                              :
                          Image.asset("lib/Images/Authentication/身份证人像页.png" ,height: 90.h,width: 150.w,),
                          onTap: () async{
                            showModalBottomSheet(context: context, builder: (BuildContext context) {
                              return Container(
                                child:
                                Stack(

                                  children: [

                                    Column(
                                      mainAxisSize: MainAxisSize.min,
                                      mainAxisAlignment:MainAxisAlignment.center,

                                      children:[

                                        SizedBox(height: 8.h,),
                                        Row(
                                          mainAxisAlignment:MainAxisAlignment.end,
                                          children: [
                                            IconButton(onPressed: (){
                                              Navigator.of(context).pop();
                                            }, icon:Icon(Icons.close,color: MyColors.textColor,)),
                                          ],
                                        ),
                                        Text(messages["示例"],style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                                        SizedBox(height: 8.h,),
                                        Image.asset('lib/Images/Authentication/身份证人像页示例图.png',width: 2270.w,height: 145.h,),


                                        SizedBox(height: 8.h,),
                                        Text(messages["请按照示例上传"],style: TextStyle(color: Color.fromRGBO(102, 102, 102, 1)),),
                                        Text(messages["模糊、遮挡会导致证件无法识别，认证不通过"],style: TextStyle(color: Color.fromRGBO(102, 102, 102, 1)),),
                                        SizedBox(height: 8.h,),
                                        Text(messages["上传照片"],style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 18.sp),),
                                        SizedBox(height: 18.h,),
                                        Row(
                                          children: [
                                            SizedBox(width: 38.w,),
                                            GestureDetector(
                                              child:   Column(
                                                children: [
                                                  Image.asset("lib/Images/Authentication/相册icon.png",width:35.w ,height: 35.h,),
                                                  Text(messages["相册"],style: TextStyle(color: Colors.black),),

                                                ],

                                              ),
                                              onTap: ()async{
                                                Navigator.of(context).pop();
                                                final pickedFile = await picker.pickImage(source: ImageSource.gallery);

                                                if (pickedFile != null) {
                                                  setState(() {
                                                    _userImage = File(pickedFile.path);
                                                    printImageMemorySize(_userImage!);

                                                    compressImage(_userImage!);

                                                  });
                                                }
                                              },
                                            ),

                                            SizedBox(width: 38.w,),
                                            GestureDetector(
                                              child: Column(
                                                children: [
                                                  Image.asset("lib/Images/Authentication/拍照icon.png",width:35.w ,height: 35.h,),
                                                  Text(messages["拍照"],style: TextStyle(color: Colors.black),),

                                                ],

                                              ),
                                              onTap: ()async{
                                                Navigator.of(context).pop();
                                                final pickedFile = await picker.pickImage(source: ImageSource.camera);

                                                if (pickedFile != null) {
                                                  setState(() {
                                                    _userImage = File(pickedFile.path);
                                                    printImageMemorySize(_userImage!);

                                                    compressImage(_userImage!);

                                                  });
                                                }
                                              },
                                            ),

                                          ],
                                        ),
                                        SizedBox(height: 30.h,),
                                      ],

                                    ),

                                  ],

                                ),
                              );


                            });

                          },
                        ),



                      ],
                    ),




                  ],
                ) ,
              ),
              SizedBox(height: 8.h,),
              Container(
                margin: EdgeInsets.only(left: 8.w,right: 8.w),
                height: 200.h,
                child:  ListView.separated(
                    physics: NeverScrollableScrollPhysics(),
                    itemCount:4,
                    separatorBuilder: (BuildContext context, int index) {
                      return Container(  // 这里使用 Divider 作为分隔符
                        color: Color.fromRGBO(248, 248, 248, 1),
                        height: 8.h,  // 分隔符的高度
                      );
                    },
                    itemBuilder:(context, index) {
                      return Padding(padding:

                      EdgeInsets.only(left: 8.w,right: 8.w),
                        child: GestureDetector(
                            child:  Container(height: 40.h,
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.all(Radius.circular(10))),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Row(
                                    children: [
                                      SizedBox(width: 8.h,),
                                      Text(titleList[index],style: TextStyle(color: Colors.black),),
                                    ],
                                  ),
                                  Row(
                                    children: [

                                      Container(
                                        width: screenSize.width-180.w,
                                        child: Text(dataList[index],textAlign: TextAlign.right,style: TextStyle(color:Colors.black,overflow:TextOverflow.ellipsis ),),
                                      ),
                                      Icon(Icons.arrow_forward_ios,color: MyColors.authTipColor,),
                                    ],
                                  ),




                                ],
                              ),
                            ),
                            onTap: () async{

                              _nametextEditingController.text =
                              dataList[index];
                              showModalBottomSheet(
                                  isDismissible: false,
                                  context: context,

                                  builder: (BuildContext context) {
                                    return Container(

                                      color: Color.fromRGBO(
                                          255, 255, 255, 1),
                                      child: Column(

                                        children: [

                                          SizedBox(height: 8.h,),
                                          Row(
                                            mainAxisAlignment: MainAxisAlignment
                                                .spaceBetween,
                                            children: [
                                              TextButton(onPressed: () {
                                                Navigator.of(context)
                                                    .pop();
                                                setState(() {
                                                  if (index == 0) {
                                                    ConName = dataList[index];
                                                  } else
                                                  if (index == 1) {
                                                    CardNum =
                                                    dataList[index];
                                                  } else
                                                  if (index == 2) {
                                                    Representative =
                                                    dataList[index];
                                                  } else
                                                  if (index == 2) {
                                                    Address =
                                                    dataList[index];
                                                  }

                                                  _nametextEditingController
                                                      .text =
                                                  dataList[index];
                                                });
                                              },
                                                  child: Text(
                                                    messages["取消"],
                                                    style: TextStyle(
                                                        color: Colors
                                                            .black),)),
                                              Text(titleList[index] +
                                                  "输入",
                                                style: TextStyle(
                                                    color: Colors.black,
                                                    fontSize: 16.sp,
                                                    fontWeight: FontWeight
                                                        .w600),),
                                              TextButton(onPressed: () {
                                                Navigator.of(context)
                                                    .pop();

                                                setState(() {
                                                  if (index == 0) {
                                                    dataList[index] = ConName;
                                                  } else
                                                  if (index == 1) {
                                                    dataList[index] =
                                                        CardNum;
                                                  } else
                                                  if (index == 2) {
                                                    dataList[index] =
                                                        Representative;
                                                  } else
                                                  if (index == 3) {
                                                    dataList[index] =
                                                        Address;
                                                  }

                                                  _nametextEditingController
                                                      .text =
                                                  dataList[index];
                                                });
                                              },
                                                child: Text(
                                                  messages["确定"],
                                                  style: TextStyle(
                                                      color: Color
                                                          .fromRGBO(
                                                          231, 112, 27,
                                                          0.85)),),),
                                            ],
                                          ),
                                          SizedBox(height: 8.h,),
                                          Container(

                                            margin: EdgeInsets.only(
                                                left: 18.w,
                                                right: 18.w),
                                            decoration: BoxDecoration(
                                              borderRadius: BorderRadius
                                                  .circular(30.0),

                                            ),
                                            child: TextField(
                                              // keyboardType: TextInputType.number,
                                                controller: _nametextEditingController,

                                                style: TextStyle(
                                                  color: Colors.black,
                                                ),
                                                decoration: InputDecoration(
                                                  filled: true,
                                                  fillColor: Color
                                                      .fromRGBO(
                                                      249, 249, 249, 1),
                                                  border: InputBorder
                                                      .none,


                                                ),
                                                onChanged: (text) {
                                                  setState(() {
                                                    if (index == 0) {
                                                      ConName = text;

                                                    } else
                                                    if (index == 1) {
                                                      CardNum = text;
                                                    } else
                                                    if (index == 2) {
                                                      Representative = text;
                                                    } else
                                                    if (index == 3) {
                                                      Address = text;
                                                    }

                                                  });
                                                }
                                            ),
                                          ),

                                        ],
                                      ),
                                    );
                                  });
                            }
                        ),
                      );
                    }
                ),
              ),



            ],
          ),
          ),
          Container(
            height: 80.h,
            color: Colors.white,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                    height: 40.h ,
                    margin: EdgeInsets.only(left: 30.w,right: 30.w),
                    decoration: BoxDecoration(
                        color:Color.fromRGBO(223, 223, 223, 1),
                        borderRadius: BorderRadius.all(Radius.circular(30))),

                    width: double.infinity,


                    child: TextButton(
                      child: Text("提交",style: TextStyle(color: Colors.white,fontSize: 14.sp),),

                      onPressed: ()async{
                        if(dataList[0]==""){
                          BrnToast.show("请输入企业名称", context, duration: BrnDuration.short,);
                        }else    if(dataList[1]==""){
                          BrnToast.show("请输入信用代码", context, duration: BrnDuration.short,);
                        }else    if(dataList[2]==""){
                          BrnToast.show("请输法人姓名", context, duration: BrnDuration.short,);
                        }else    if(dataList[3]==""){
                          BrnToast.show("请输入地址", context, duration: BrnDuration.short,);
                        }else {
                          String? token = await TokenManager.getToken();
                          dio.interceptors.add(InterceptorsWrapper(
                              onRequest: (options, handler) {
                                options.headers["satoken"] = token;
                                return handler.next(options);
                              }
                          ));
                          dio
                              .post(
                            MyServiceUrl.header + 'api/auth/co/company/add',
                            data: {
                              "name": dataList[0],
                              "taxNum": dataList[1],
                              "legalName": dataList[2],
                              "registerAddress": dataList[3],
                              "frontPath": getFrontPath,
                            },
                            options: Options(
                              sendTimeout: Duration(seconds: 2),
                              receiveTimeout: Duration(seconds: 5),
                            ),

                          )
                              .then((r) {
                            setState(() {
                              print(r);
                              Map<String, dynamic> jsonMap = json.decode(
                                  r.toString());
                              // 获取code和data
                              String code = jsonMap['code'].toString();
                              if (code == "200") {
                                print("code：$code");
                                BrnToast.show("提交成功", context, duration: BrnDuration.short,);

                                Navigator.pushReplacement(
                                  context,
                                  MaterialPageRoute(builder: (context) => TabbarView(pateIndex: 3,),fullscreenDialog: true,),
                                );
                              }
                            });
                          }).catchError((error) {
                            print(error);
                            ;
                          });
                        }
                      },
                    )
                ),
              ],
            ),
          ),



          // }),
        ],
      ),
    );
  }
}
